package com.panyunting.notepad.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.panyunting.notepad.Api;
import com.panyunting.notepad.R;

import org.xml.sax.helpers.LocatorImpl;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    Button loginbtn , registbtn ;
    EditText nameed ,passed;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 1:
                    JSONObject jsonObject = JSONObject.parseObject(msg.obj.toString());
                    if(jsonObject.getIntValue("code") == 2) {
                        Toast.makeText(LoginActivity.this,jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                    }
                    if(jsonObject.getIntValue("code") == 1) {
                        SharedPreferences.Editor editor = getSharedPreferences("info", MODE_PRIVATE).edit();
                        editor.putString("username",nameed.getText().toString()).commit();
                        Toast.makeText(LoginActivity.this,("登录成功!"),Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(LoginActivity.this,NotePadActivity.class));
                        finish();
                    }
                    break;
                case 2:
                    JSONObject registjson = JSONObject.parseObject(msg.obj.toString());
                    if(registjson.getIntValue("code") == 2) {
                        Toast.makeText(LoginActivity.this,registjson.getString("message"),Toast.LENGTH_SHORT).show();
                    }
                    if(registjson.getIntValue("code") == 1) {
                        Toast.makeText(LoginActivity.this,("注册成功，请登录!"),Toast.LENGTH_SHORT).show();
//                        startActivity(new Intent(LoginActivity.this,NotePadActivity.class));
//                        finish();
                    }
                    break;
                case 3:
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        nameed = findViewById(R.id.editusername);
        passed = findViewById(R.id.editpassword);

        loginbtn=  findViewById(R.id.loginbtn);
        registbtn = findViewById(R.id.registbtn);

        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login();
            }
        });
        registbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                regist();
            }
        });
    }
    void regist () {
        OkHttpClient client = new OkHttpClient();

        final MediaType mediaType = MediaType.parse("application/json");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username",nameed.getText().toString());
        jsonObject.put("password",passed.getText().toString());
        RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toJSONString() );
        Request request = new Request.Builder()
                .url(Api.RegisterServlet)
                .post(requestBody)
                .addHeader("content-type", "application/json")
                .addHeader("cache-control", "no-cache")
                .build();
        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(LoginActivity.this, "Post Failed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("TAG", "run: " + res);
                        Message ms   = new Message();
                        ms.what =2 ;
                        ms.obj = res;
                        handler.sendMessage(ms);
                    }
                });
            }
        });
    }
    void login () {
        OkHttpClient client = new OkHttpClient();

        final MediaType mediaType = MediaType.parse("application/json");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username",nameed.getText().toString());
        jsonObject.put("password",passed.getText().toString());
        RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toJSONString() );
        Request request = new Request.Builder()
                .url(Api.LoginServlet)
                .post(requestBody)
                .addHeader("content-type", "application/json")
                .addHeader("cache-control", "no-cache")
                .build();
        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(LoginActivity.this, "Post Failed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("TAG", "run: " + res);
                        Message ms   = new Message();
                        ms.what =1 ;
                        ms.obj = res;
                        handler.sendMessage(ms);
                    }
                });
            }
        });
    }
}
